/**
 * @file Driver_Spi.c
 * @brief 软件SPI驱动，来源于江协科技。
 * @author 2bam 
 * @version 1.0
 * @date 2024-11-24
 * @copyright Copyright (c) 2024  NULL
 * 
 * @change log:
 * Date           Version Author   Describe
 * 2024-11-24     1.0     2bam     first version
 * 
 */


/* Includes -------------------------------------------------------------------*/
#include "main.h"
#include "Driver_Spi.h"
/* define ---------------------------------------------------------------------*/

/* typedef --------------------------------------------------------------------*/

/* variables ------------------------------------------------------------------*/

/* Private function prototypes ------------------------------------------------*/



/**
 * @brief 
 * @param  value       My Param doc
 * @date 2024-11-24
 * @author 2bam 
 */
static void SoftSpi_Write_SS(uint8_t value)
{
    HAL_GPIO_WritePin(W25Q16_CS_GPIO_Port,W25Q16_CS_Pin,(GPIO_PinState)value);
}

/**
 * @brief 
 * @param  value       My Param doc
 * @date 2024-11-26
 * @author 2bam 
 */
static void SoftSpi_Write_SCK(uint8_t value)
{
    HAL_GPIO_WritePin(W25Q16_SCK_GPIO_Port,W25Q16_SCK_Pin,(GPIO_PinState)value);
}

/**
 * @brief 
 * @param  value       My Param doc
 * @date 2024-11-26
 * @author 2bam 
 */
static void SoftSpi_Write_MOSI(uint8_t value)
{
    HAL_GPIO_WritePin(W25Q16_MOSI_GPIO_Port,W25Q16_MOSI_Pin,(GPIO_PinState)value);
}

/**
 * @brief 
 * @return uint8_t 
 * @date 2024-11-26
 * @author 2bam 
 */
static uint8_t SoftSpi_Read_MISO(void)
{
    return (uint8_t)HAL_GPIO_ReadPin(W25Q16_MISO_GPIO_Port,W25Q16_MISO_Pin);
}

/**
 * @brief 
 * @date 2024-11-24
 * @author 2bam 
 */
void SoftSpiInit(void)
{
    SoftSpi_Write_SS(1);
    SoftSpi_Write_SCK(0);
}

/**
 * @brief 
 * @date 2024-11-26
 * @author 2bam 
 */
void SoftSpiStart(void)
{
    SoftSpi_Write_SS(0);
}

/**
 * @brief 
 * @date 2024-11-26
 * @author 2bam 
 */
void SoftSpiStop(void)
{
    SoftSpi_Write_SS(1);
}


/**
 * @brief 
 * @param  byte        My Param doc
 * @return uint8_t 
 * @date 2024-11-26
 * @author 2bam 
 */
uint8_t SoftSpiSwapByte(uint8_t byte)
{
    uint8_t byte_receive = 0x00;
    uint8_t i = 0;

    for (i = 0; i < 8; i++)
    {
        SoftSpi_Write_MOSI(byte&(0x80>>i));
        SoftSpi_Write_SCK(1);
        if(SoftSpi_Read_MISO())
        {
            byte_receive |= (0x80>>i);
        }
        SoftSpi_Write_SCK(0);
    }
    return byte_receive;
}

